package com.example.a13001.shoppingmalltemplate.activitys;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.a13001.shoppingmalltemplate.MainActivity;
import com.example.a13001.shoppingmalltemplate.R;
import com.example.a13001.shoppingmalltemplate.application.ShoppingMallTemplateApplication;
import com.example.a13001.shoppingmalltemplate.base.AppConstants;
import com.example.a13001.shoppingmalltemplate.base.BaseActivity;
import com.example.a13001.shoppingmalltemplate.manager.DataManager;
import com.example.a13001.shoppingmalltemplate.modle.User;
import com.example.a13001.shoppingmalltemplate.utils.MyUtils;
import com.example.a13001.shoppingmalltemplate.utils.SPUtils;
import com.example.a13001.shoppingmalltemplate.utils.Utils;


import java.io.File;
import java.util.HashMap;
import java.util.Iterator;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by Administrator on 2017/4/1.
 */

public class AdActivity extends BaseActivity {
    private ShoppingMallTemplateApplication model;
    private String appPath="shopmall";
    private ImageView adImage;
    private TextView adtext;
    private int djs=5;
    private Handler mHandler = new Handler();
    private static final String TAG = "AdActivity";
    private User mUser;
    private DataManager manager;
    private CompositeSubscription mCompositeSubscription;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        model=(ShoppingMallTemplateApplication) getApplicationContext();
        //加载广告窗体
        setContentView(R.layout.activity_ad);
        manager = new DataManager(AdActivity.this);
        mCompositeSubscription = new CompositeSubscription();
        adImage=(ImageView) findViewById(R.id.adImage);
        //指定下载路径为系统下载文件夹
//        String path = Environment.getExternalStorageDirectory() + "/" + appPath + "/" + Utils.md5(String.valueOf(model.getAdId())) + ".jpg";
        int photoId = (int) SPUtils.get(AppConstants.photoId, 0);
        String path = Environment.getExternalStorageDirectory() + "/" + appPath + "/" +photoId +".jpg";
        File filename=new File(path);
        if (filename.exists()){
            //加载广告图片
            Uri uri = Uri.fromFile(new File(path));
            adImage.setImageURI(uri);
        }
        adtext=(TextView) findViewById(R.id.adtext);
        adtext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHandler.removeCallbacks(runnable);
                String logintype = (String) SPUtils.get("logintype", "");
                String safetyCode = MyUtils.getMetaValue(AdActivity.this, "safetyCode");
                String code = Utils.md5(safetyCode + Utils.getTimeStamp());
                String timestamp = Utils.getTimeStamp();
                if (!TextUtils.isEmpty(logintype)) {

                    switch (logintype) {
                        case "phone":
                            ShoppingMallTemplateApplication.loginType = "phone";
                            String username = MyUtils.getUserName();
                            String pwd = MyUtils.getUserPwd();
                            if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(pwd)) {

                                Log.e(TAG, "handleMessage: " + code + "==" + Utils.getTimeStamp() + "==" + username + "--" + pwd);
                                doLogin(AppConstants.COMPANY_ID, code, Utils.getTimeStamp(), username, pwd, AppConstants.FROM_MOBILE);

                            } else {
                                Intent intent=new Intent(AdActivity.this, MainActivity.class);
                                intent.putExtra("type", "Splash");
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置
                                startActivity(intent);
                                finish();
                            }
                            break;
                        case "wechat":
//                               String  openid= (String) SPUtils.get("openid","");
//                               String  nickname= (String) SPUtils.get("nickname","");
//                               String  sex= (String) SPUtils.get("sex","");
//                               String  headimgurl= (String) SPUtils.get("headimgurl","");
                            ShoppingMallTemplateApplication.loginType = "wechat";
//                                doThirdLogin(AppConstants.COMPANY_ID,code,timestamp,AppConstants.LOGINTYPE_WECHAT,openid,nickname,sex,headimgurl);
                            Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                            thirdLogin(wechat);
                            break;
                        case "qq":
                            ShoppingMallTemplateApplication.loginType = "qq";
//                                doThirdLogin(AppConstants.COMPANY_ID,code,timestamp,AppConstants.LOGINTYPE_WECHAT,openid,nickname,sex,headimgurl);
                            Platform qq = ShareSDK.getPlatform(QQ.NAME);
                            thirdLogin(qq);
                            break;
                    }

                } else {
                    Intent intent = new Intent(AdActivity.this, MainActivity.class).putExtra("type", "Splash");
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置
                    startActivity(intent);
                    finish();
                }

            }
        });
        //广告倒计时，使用线程进行倒计时
        mHandler.postDelayed(runnable, 1000);
        //广告图片增加点击事件
        adImage.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                mHandler.removeCallbacks(runnable);
                String photoPath  = (String) SPUtils.get(AppConstants.photoPath, "");
                String photoLink  = (String) SPUtils.get(AppConstants.photoLink, "");
                String photoName  = (String) SPUtils.get(AppConstants.photoName, "");
                Intent intent = new Intent(AdActivity.this, AdWindow.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置
                intent.putExtra("content_url", photoLink);
                intent.putExtra("content_title",photoName);
                intent.putExtra("content_fx", 1);
                intent.putExtra("content_type", "admainwebview");
                startActivity(intent);
                AdActivity.this.finish();
            }
        });
    }

    Runnable runnable=new Runnable(){
        @Override
        public void run() {
            // TODO Auto-generated method stub
            //要做的事情，这里再次调用此Runnable对象，以实现每两秒实现一次的定时器操作
            djs--;
            Log.e(TAG, "run: "+djs );
            String djsText=getResources().getString(R.string.adtime);
            djsText=djsText.replace("5", String.valueOf(djs));
            adtext.setText(djsText);//让广告文字中的数字动起来
            if (djs==0){
                //倒计时3秒进入主界面
                String logintype = (String) SPUtils.get("logintype", "");
                String safetyCode = MyUtils.getMetaValue(AdActivity.this, "safetyCode");
                String code = Utils.md5(safetyCode + Utils.getTimeStamp());
                String timestamp = Utils.getTimeStamp();
                if (!TextUtils.isEmpty(logintype)) {

                    switch (logintype) {
                        case "phone":
                            ShoppingMallTemplateApplication.loginType = "phone";
                            String username = MyUtils.getUserName();
                            String pwd = MyUtils.getUserPwd();
                            if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(pwd)) {

                                Log.e(TAG, "handleMessage: " + code + "==" + Utils.getTimeStamp() + "==" + username + "--" + pwd);
                                doLogin(AppConstants.COMPANY_ID, code, Utils.getTimeStamp(), username, pwd, AppConstants.FROM_MOBILE);

                            } else {
                                Intent intent=new Intent(AdActivity.this, MainActivity.class);
                                intent.putExtra("type", "Splash");
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置
                                startActivity(intent);
                                finish();
                            }
                            break;
                        case "wechat":
//                               String  openid= (String) SPUtils.get("openid","");
//                               String  nickname= (String) SPUtils.get("nickname","");
//                               String  sex= (String) SPUtils.get("sex","");
//                               String  headimgurl= (String) SPUtils.get("headimgurl","");
                            ShoppingMallTemplateApplication.loginType = "wechat";
//                                doThirdLogin(AppConstants.COMPANY_ID,code,timestamp,AppConstants.LOGINTYPE_WECHAT,openid,nickname,sex,headimgurl);
                            Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                            thirdLogin(wechat);
                            break;
                        case "qq":
                            ShoppingMallTemplateApplication.loginType = "qq";
//                                doThirdLogin(AppConstants.COMPANY_ID,code,timestamp,AppConstants.LOGINTYPE_WECHAT,openid,nickname,sex,headimgurl);
                            Platform qq = ShareSDK.getPlatform(QQ.NAME);
                            thirdLogin(qq);
                            break;
                    }

                } else {
                    Intent intent = new Intent(AdActivity.this, MainActivity.class).putExtra("type", "Splash");
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置
                    startActivity(intent);
                    finish();
                }
//                Intent intent = new Intent(AdActivity.this, MainActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置
//                startActivity(intent);
//                AdActivity.this.finish();
            }
            mHandler.postDelayed(this, 1000);
        }
    };
    /**
     * 登录
     *
     * @param companyid 站点ID
     * @param code      安全校验码
     * @param timestamp 时间戳
     * @param name      会员名称，用户名/手机/邮箱
     * @param pwd       登录密码
     * @param from      来源，pc 电脑端 mobile 移动端
     */
    public void doLogin(String companyid, String code, String timestamp, String name, String pwd, String from) {
        mCompositeSubscription.add(manager.doLogin(companyid, code, timestamp, name, pwd, from)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<User>() {
                               @Override
                               public void onCompleted() {
                                   int status=mUser.getStatus();
                                   if (status>0){
                                       Intent intent=new Intent(AdActivity.this, MainActivity.class);
                                       intent.putExtra("type","Splash");
                                       intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置
                                       startActivity(intent);
                                       finish();
                                   }else{
//                                       Toast.makeText(AdActivity.this, ""+mUser.getReturnMsg(), Toast.LENGTH_SHORT).show();
                                       Intent intent = new Intent(AdActivity.this, MainActivity.class).putExtra("type","Splash");
                                       intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置
                                       startActivity(intent);
                                       finish();
                                   }
                               }

                               @Override
                               public void onError(Throwable e) {
                                   Log.e(TAG, "onError: "+e.toString() );
                                   Toast.makeText(AdActivity.this, "数据请求失败", Toast.LENGTH_SHORT).show();
                               }

                               @Override
                               public void onNext(User user) {
                                   Log.e(TAG, "onNext: "+user.toString() );
                                   mUser=user;

                               }
                           }

                ));
    }
    private void thirdLogin(Platform platform) {
        Log.e(TAG, "onComplete: "+"aaaaa");
//        if (platform.isAuthValid()) {
//            Log.e(TAG, "onComplete: "+"cccccc");
//            platform.removeAccount(true);
//            return;
//        }
        Log.e(TAG, "onComplete: "+"bbbbbb");
        platform.setPlatformActionListener(new PlatformActionListener() {

            private String sex;

            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Log.e(TAG, "onComplete: "+i );
                if (i == Platform.ACTION_USER_INFOR) {
                    PlatformDb platDB = platform.getDb();//获取数平台数据DB
                    //通过DB获取各种数据
                    platDB.getToken();
                    platDB.getUserGender();
                    String icon = platDB.getUserIcon();
                    String profit = platDB.getUserId();
                    String nickname = platDB.getUserName();
                    String openid = platDB.getUserId();
                    String gender=platDB.getUserGender();
                    Iterator ite =hashMap.entrySet().iterator();
                    if("m".equals(gender)){
                        sex="1";
                    } else {
                        sex="2";
                    }

                    Log.e(TAG, "onComplete: "+icon+"profit="+profit+"nickname="+nickname+"openid="+openid+"gender="+gender+"sex="+sex);
                    String safetyCode = MyUtils.getMetaValue(AdActivity.this, "safetyCode");
                    String code= Utils.md5(safetyCode+Utils.getTimeStamp());
                    doThirdLogin(AppConstants.COMPANY_ID,code,Utils.getTimeStamp(),AppConstants.LOGINTYPE_WECHAT,openid,nickname,sex,icon,AppConstants.androidos,MyUtils.getImei(),platform);
//                    isThirdLogin(icon, profit, nickname);
                }
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.e("aaa",
                        "(LoginActivity.java:159)" + "onError");
            }

            @Override
            public void onCancel(Platform platform, int i) {
                Log.e("aaa",
                        "(LoginActivity.java:165)" + "onCancel");
            }
        });
        platform.showUser(null);
    }
    /**
     * 第三方登录
     * @param companyid   站点ID
     * @param code        安全校验码
     * @param timestamp   时间戳
     * @param type        qqlogin QQ登录， wxlogin 微信登录，sinalogin 新浪微博登录
     * @param openid      第三方登录用户唯一值
     * @param nickname    会员昵称
     * @param sex          会员性别，1 男，2 女
     * @param headimgurl   头像地址
     * @param platform
     * @return
     */
    public void doThirdLogin(String companyid, String code, String timestamp, String type, String openid, String nickname, String sex, String headimgurl,String appos,String appkey, final Platform platform) {
        mCompositeSubscription.add(manager.doThirdLogin(companyid,code,timestamp,type,openid,nickname,sex,appos,appkey,headimgurl)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<User>() {
                               @Override
                               public void onCompleted() {
                                   Log.e(TAG, "onCompleted: "+mUser.toString());
                                   int status=mUser.getStatus();
                                   if (status>0){
                                       if ("QQ".equals(platform.getName())){
                                           ShoppingMallTemplateApplication.loginType="qq";
                                       }else{
                                           ShoppingMallTemplateApplication.loginType="wechat";
                                       }
                                       Intent intent=new Intent(AdActivity.this, MainActivity.class);
                                       intent.putExtra("type","Splash");
                                       intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置
                                       startActivity(intent);
                                       finish();
                                   }else{
                                       Toast.makeText(AdActivity.this, ""+mUser.getReturnMsg(), Toast.LENGTH_SHORT).show();
                                   }
                               }

                               @Override
                               public void onError(Throwable e) {
                                   Log.e(TAG, "onError: "+e.toString() );
                                   Toast.makeText(AdActivity.this, "数据请求失败", Toast.LENGTH_SHORT).show();
                               }

                               @Override
                               public void onNext(User user) {
                                   Log.e(TAG, "onNext: "+user.toString() );
                                   mUser=user;

                               }
                           }

                ));
    }
}